package com.easyCode.dataMock.dataGenerator;

import com.easyCode.EasyGeneratorAutoConfiguration;
import com.easyCode.dataMock.FieldMockInfo;
import com.easyCode.dataMock.utils.ByteUtils;
import com.easyCode.util.StringUtil;
import org.springframework.util.Assert;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

import static com.easyCode.dataMock.constants.DefaultDictConstants.DEFAULT_DICT_PATH_PREFIX;

/**
 * 字典中每个值通过英文的','分隔开来
 *
 * @author 大忽悠
 * @create 2023/1/18 12:00
 */
public class DictDataGenerator implements DataGenerator {
    private final Map<String, String[]> dictCache = new HashMap<>();
    /**
     * 默认词库中单词采用的分隔符号
     */
    private static final String DEFAULT_DELIMITER=",";

    /**
     * @param fieldMockInfo 字段信息
     * @return 返回模拟生成的data
     */
    @Override
    public String generator(FieldMockInfo fieldMockInfo) {
        String dictPath = fieldMockInfo.getExtra()[0];
        String[] dict = dictCache.get(dictPath);
        if (dict == null) {
            //默认字典去类路径下找
            if (dictPath.startsWith(DEFAULT_DICT_PATH_PREFIX)) {
                InputStream inputStream = EasyGeneratorAutoConfiguration.class.getClassLoader().getResourceAsStream(dictPath);
                Assert.notNull(inputStream, "无法寻找到默认的字典文件: " + dictPath);
                dict = new String(ByteUtils.readBytes(inputStream)).split(DEFAULT_DELIMITER);
            } else {
                try (FileInputStream inputStream = new FileInputStream(dictPath)) {
                    dict = new String(ByteUtils.readBytes(inputStream)).split(fieldMockInfo.getExtra().length==2? fieldMockInfo.getExtra()[1]:DEFAULT_DELIMITER);
                    //过滤掉字典中空白字符
                    dict = Arrays.stream(dict).filter(s->!StringUtil.isNullOrEmpty(s)).toArray(String[]::new);
                } catch (IOException e) {
                    throw new RuntimeException("无法寻找到字典文件: " + dictPath);
                }
            }
            dictCache.put(dictPath, dict);
        }
        //字典中随机挑选一个值返回
        return dict[ThreadLocalRandom.current().nextInt(dict.length)];
    }
}
